
// vuex 的使用  详情参考官网 https://uniapp.dcloud.io/vue-vuex
// import store from '../store/index.js'
import common from './common.js'

export default class Request {
    http(param) {
        // 请求参数
        var url = param.url,
            method = param.method,
            header = param.header || {'content-type': "application/json"},
            data = param.data || {},
            token = param.token || "",
            hideLoading = param.hideLoading || false;

        //拼接完整请求地址
        var requestUrl = common.requestUrl + url;

        //请求方式:GET或POST(POST需配置
        // header: {'content-type' : "application/x-www-form-urlencoded"},)
		
     //    if (method) {
     //        method = method.toUpperCase(); //小写改为大写
     //        if (method == "POST") {
     //            header = {
     //                // 'content-type': "application/x-www-form-urlencoded"
					// 'content-type': "application/json"
     //            };
     //        } else {
     //            header = {
     //                'content-type': "application/json"
     //            };
     //        }
     //    }

        //加载圈
        if (!hideLoading) {
            uni.showLoading({
                title: '加载中...'
            });
        }
		
		let access_token = common.getAccessToken();
		if (access_token) {
			header['Authorization'] = 'Bearer ' + access_token;
		}
		

        // 返回promise
        return new Promise((resolve, reject) => {
            // 请求
            uni.request({
                url: requestUrl,
                data: data,
                method: method,
                header: header,
                success: (res) => {
					console.log(res);
					
					if (res.statusCode == 401) {
						console.log(1231)
						// token过期
						uni.showToast({
							title: '请先进行登录操作',
							duration: 2000,
							icon: 'none',
						})
						setInterval(function() {
							uni.navigateTo({url: '/pages/user/signin'});
						}, 2000);
					}
					
					if (res.data.meta.code != '000') {
						uni.showToast({
							title: res.data.meta.msg,
							duration: 2000,
							icon: 'none',
						})
						// resolve(res.data)
						// reject();return;
					}
					
					if (res.data.meta.code == '000') {
						// 将结果抛出
						resolve(res.data)
					}
                    
                },
                //请求失败
                fail: (e) => {
					console.log(e.data)
                    reject(e.data);
                },
                //请求完成
                complete() {
                    //隐藏加载
                    if (!hideLoading) {
                        uni.hideLoading();
                    }
                    resolve();
                    return;
                }
            })
        })
    }
}